//
//  SYUserAccountViewModel.swift
//  YANAWeibo
//
//  Created by mac on 16/5/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class SYUserAccountViewModel: NSObject {
    //单利全局访问点
    static let sharedUserAccount: SYUserAccountViewModel = SYUserAccountViewModel()
    
    override init() {
        super.init()
        userAccount = SYUserAccount.loadUserAccount()
    }
    
    var isLogin: Bool {
        return accessToken != nil
    }
    
    var accessToken: String? {
        guard let token = userAccount?.access_token else {
            return nil
        }
        //判断token是够过期
        let result = userAccount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending {
            //代表没有过期
            return token
        }else{
            return nil
        }
        
    }
    
    //保存用户对象
    var userAccount: SYUserAccount?
    
    //封装网络接口
    //获取accesstoken
    func requestAccessToken(code: String, complete: (isSuccess: Bool)->()) {
        
        SYNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            //解析数据
            guard let dic = response as? [String: AnyObject] else {
                print("数据不是json格式")
                complete(isSuccess: false)
                return
            }
            //代码执行到此，一定是字典
            let uerAccout = SYUserAccount(dic: dic)
            self.requestedUserInfo(uerAccout, complete: complete)
            
        }
    }
    
    // 获取用户信息
    func requestedUserInfo(userAccount: SYUserAccount, complete: (isSuccess: Bool)->()) {
        
        SYNetWorkTools.sharedTools.requestedUserInfo(userAccount) { (response, error) -> () in
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false)
                return
            }
            //判断json格式
            guard let dic = response as? [String: AnyObject] else {
                print("不是一个正确的json格式")
                complete(isSuccess: false)
                return
            }
            userAccount.name = dic["name"] as? String
            userAccount.avatar_large = dic["avatar_large"] as? String
            
            //设置用户数据
            self.userAccount = userAccount
            //归档
            let result = userAccount.saveUserAccount()
            if result {
                complete(isSuccess: true)
            }else{
                complete(isSuccess: false)
            }
            
        }
    }

    
    

    

}
